package com.tigerhhzz.springcloud.controller;

import com.tigerhhzz.springcloud.entities.CommonResult;
import com.tigerhhzz.springcloud.entities.Payment;
import com.tigerhhzz.springcloud.ribbonmylb.MyRibbonLoadBalaner;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author tigerhhzz
 * @date 2023/4/13 9:22
 */
@RestController
@Slf4j
public class OrderController {

    //public static final String PAYENT_URL = "http://localhost:8001";
    public static final String PAYENT_URL = "http://cloud-payment-service";
    //注入远程服务调用
    @Resource
    private RestTemplate restTemplate;
    //注入服务发现
    @Resource
    private DiscoveryClient discoveryClient;

    //注入自己定义的负载均衡变量
    @Resource
    private MyRibbonLoadBalaner myRibbonLoadBalaner;

    /*调用订单支付模块中的创建新记录接口*/   //由于使用了自己手写了的负载均衡算法 resttemplate调用的方法也要采用相应算法的方法（这里面其实就是调用的host路径发生了变化）
    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){

        return restTemplate.postForObject(PAYENT_URL+"/payment/create",payment,CommonResult.class);
    }
    /*调用订单支付模块中的查询记录接口*/   //由于使用了自己手写了的负载均衡算法 resttemplate调用的方法也要采用相应算法的方法（这里面其实就是调用的host路径发生了变化）
    @GetMapping("/consumer/payment/getById/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") long id) {
        return restTemplate.getForObject(PAYENT_URL+"/payment/getById/"+id,CommonResult.class);
    }

    /*返回响应体 接口*/
    @GetMapping("/consumer/payment/getForEnity/{id}")  //这是采用自己手的负载均衡算法的接口 测试成功       由于使用了自己手写了的负载均衡算法 resttemplate调用的方法也要采用相应算法的方法（这里面其实就是调用的host路径发生了变化）
    public CommonResult<Payment> getPaymentForEnity(@PathVariable("id") long id){

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        System.out.println(instances);
        if (instances == null || instances.size() == 0) {
            return null;
        }
        ServiceInstance serviceInstance = myRibbonLoadBalaner.instance(instances);
        URI uri = serviceInstance.getUri();

        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(uri + "/payment/getById/" + id, CommonResult.class);
        if(forEntity.getStatusCode().is2xxSuccessful()){
            return forEntity.getBody();
        }else {
            return new CommonResult<>(444,"操作失败");
        }
    }


    /*服务注册中心 查询微服务接口*/
    @GetMapping(value = "/consumer/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for(String element : services){
            log.info("******element:  "+element);
        }

        log.info("------------------------------");

        List<ServiceInstance> instances1 = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for(ServiceInstance instance : instances1){
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }

        log.info("------------------------------");

        List<ServiceInstance> instances2 = discoveryClient.getInstances("CLOUD-COMSUMER-ORDER80");
        for(ServiceInstance instance : instances2){
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }

        return this.discoveryClient;
    }


    //    自己手写的负载均衡算法测试接口
    @GetMapping("/consumer/payment/lb")
    public String getPaymentLB() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        System.out.println(instances);
        if (instances == null || instances.size() == 0) {
            return null;
        }
        ServiceInstance serviceInstance = myRibbonLoadBalaner.instance(instances);
        URI uri = serviceInstance.getUri();
        System.out.println(uri+"/payment/lb");
        return restTemplate.getForObject(uri+"/payment/lb",String.class);
    //        return uri+"/payment/lb";
    }


    /*测试zipkin sleuth接口*/
    @GetMapping("/consumer/payment/zipkin")
    public String paymentZipkin(){
        String result = restTemplate.getForObject("http://localhost:8001"+"/payment/zipkin/",String.class);
        return result;
    }

}
